package fr.ul.ade.prime.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

import com.actionbarsherlock.app.SherlockFragmentActivity;

import fr.ul.ade.prime.service.AdeWebService;
import fr.ul.ade.prime.service.AdeWebServiceBinder;

/**
 * Handles the connection to the service for sub-classes of this class.
 * 
 * @author		Schnell Michaël
 * @version		1.0
 */
public class AdeWebFragmentActivity extends SherlockFragmentActivity {

	protected static final String TAG = AdeWebFragmentActivity.class.getSimpleName() ;

	protected AdeWebService service ;

	protected ServiceConnection serviceConnection ;

	/**
	 * Binds this activity to the AdeWeb service.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState) ;
	}// onCreate(Bundle)
	
	@Override
	protected void onStart() {
		super.onStart() ;
		
		// Binds the activity to the service and adds a connection listener
		Intent serviceIntent = new Intent(AdeWebService.class.getName()) ;
		this.serviceConnection = new ServiceConnectionAdapter(this) ;
		this.bindService(serviceIntent, this.serviceConnection, Context.BIND_AUTO_CREATE) ;
	}
	
	@Override
	protected void onStop() {
		super.onStop() ;
		this.unbindService(this.serviceConnection) ;
	}

	protected class ServiceConnectionAdapter implements ServiceConnection {
		
		protected AdeWebFragmentActivity activity ;

		protected ServiceConnectionAdapter(AdeWebFragmentActivity activity) {
			super() ;
			this.activity = activity ;
		}// ServiceConnectionAdapter(AdeWebActivity)

		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {
			this.activity.service = ((AdeWebServiceBinder) binder).getService() ;
		}// onServiceConnected(ComponentName, IBinder)

		@Override
		public void onServiceDisconnected(ComponentName name) {
			this.activity.service = null ;
		}// onServiceDisconnected(ComponentName)

	}// class ServiceConnectionAdapter

}// class AdeWebActivity